#include <iostream>
#include <cstdlib>
#include <cstring>
#include <cassert>
#include <cerrno>
#include <netinet/in.h>
#include <arpa/inet.h>
#include <sys/socket.h>
#include <unistd.h>

using namespace std;

const int BUFFER_SIZE = 1024;

int main(int argc, char* argv[])
{
    if (argc <= 2)
    {
        cerr << "Usage: " << argv[0] << " <server> <port>" << endl;
        return 1;
    }
    const char* ip = argv[1];
    int port = atoi(argv[2]);

    struct sockaddr_in address;
    memset(&address, 0, sizeof(address));
    address.sin_family = AF_INET;
    address.sin_port = htons(port);
    inet_pton(AF_INET, ip, &address.sin_addr);

    // 创建套接字
    int sockfd = socket(AF_INET, SOCK_STREAM, 0);
    assert(sockfd >= 0);

    // 设置接收缓冲区大小
    int recvbuf = atoi(argv[3]);
    int len = sizeof(recvbuf);
    setsockopt(sockfd, SOL_SOCKET, SO_RCVBUF, &recvbuf, len);
    getsockopt(sockfd, SOL_SOCKET, SO_RCVBUF, &recvbuf, (socklen_t*)&len);
    cout << "The receive buffer size after setting is: " << recvbuf << endl;

    // 绑定套接字
    int ret = bind(sockfd, (struct sockaddr*)&address, sizeof(address));
    assert( ret != -1);

    // 监听套接字
    ret = listen(sockfd, 5);
    assert(ret != -1);

    // 连接客户端
    struct sockaddr_in client;
    socklen_t client_addrlength = sizeof(client);
    int connfd = accept(sockfd, (struct sockaddr*)&client, &client_addrlength);
    if( connfd < 0)
    {
        cout << "errno is: " << errno << endl;
    }
    else
    {
        char buffer[BUFFER_SIZE];
        memset(buffer, 0, BUFFER_SIZE);
        // 服务器循环处理业务
        while(recv(connfd, buffer, BUFFER_SIZE-1, 0) > 0)
        {
            cout << "Received data: " << buffer << endl;
            memset(buffer, 0, BUFFER_SIZE); // 清空缓冲区
        }
        close(connfd);
    }
    close(sockfd);

    return 0;
}